import { User } from "../models/user.model.js"
import bcryptjs from "bcryptjs"
import { genTokenAndSetCookie } from "../utils/genToken.js"

export const signup = async (req, res) => {
    try {
        const { email, password } = req.body
        if (!email || !password) {
            return res.status(400).json({
                success: false,
                message: "email and password are required"
            })
        }

        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(email)) {
            return res.status(400).json({
                success: false,
                message: "Invalid email",
            })
        }

        if (password.length < 6) {
            return res.status(400).json({
                success: false,
                message: "Password must be at least length 6",
            })
        }

        const existingUserByEmail = await User.findOne({
            email: email,
        })
        if (existingUserByEmail) {
            return res.status(400).json({
                success: false,
                message: "Email already exists",
            })
        }

        const salt = await bcryptjs.genSalt(10)
        const hashedPassword = await bcryptjs.hash(password, salt)

        const PROFILE_PICS = ["/avatar1.png", "/avatar2.png", "/avatar3.png"]

        const image = PROFILE_PICS[Math.floor(Math.random() * PROFILE_PICS.length)]

        const newUser = new User({
            email,
            password: hashedPassword,
            image,
        })

        const token = await genTokenAndSetCookie(newUser._id, res)
        await newUser.save()

        res.status(201).json({
            success: true,
            message: {
                ...newUser._doc,
                token: token,
            }
        })
    } catch (error) {
        console.log(`Error in ${__filename}@signUp: `, error.message)
        res.status(500).json({
            success: false,
            message: "Internal Server Error",
        })
    }
}

export const login = async (req, res) => {
    try {
        const { email, password } = req.body
        if (!email || !password) {
            return res.status(400).json({
                success: false,
                message: "email and password are required",
            })
        }

        const user = await User.findOne({ email: email })
        if (!user) {
            res.status(404).json({
                success: false,
                message: "User not found",
            })
        }

        const isPasswordCorrect = await bcryptjs.compare(password, user.password)
        if (!isPasswordCorrect) {
            res.status(400).json({
                success: false,
                message: "User not found or Password error",
            })
        }

        const token = genTokenAndSetCookie(user._id, res)

        res.status(200).json({
            success: true,
            user: {
                ...user._doc,
                token: token,
            },
        })
    } catch (error) {
        console.log(`Error in ${__filename}@login: `, error.message)
        res.status(500).json({
            success: false,
            message: "Internal Server Error",
        })
    }
}

export const logout = async (req, res) => {
    try {
        res.clearCookie("jwt-netflix")
        res.status(200).json({
            success: true,
            message: "Logged out successfully",
        })
    } catch (error) {
        console.log(`Error in ${__filename}@logout: `, error.message)
        res.status(500).json({
            success: false,
            message: "Internal Server Error",
        })
    }
}

export const authCheck = async (req, res) => {
    try {
        console.log("req user: ", req.user)
        res.status(200).json({
            success: true,
            user: req.user,
        })
    } catch (error) {
        console.log(`Error in ${__filename}@authCheck: `, error.message)
        res.status(500).json({
            success: false,
            message: "Internal Server Error",
        })
    }
}